const state = {
  loading: 0,
  loaded: 1,
  error: 2
};

export class ImageManager {
  constructor(options) {
    this.el = options.el;
    this.src = options.src;
    this.state = state.loading;
    this.loading = options.loading;
    this.error = options.error;
    this.render(this.loading);
  }
  render() {
    this.el.setAttribute("src", src);
  }
  load(next) {
    if (this.state > state.loading) {
      return;
    }
    this.renderSrc(next);
  }
  renderSrc(next) {
    loadImage(this.src)
      .then(() => {
        this.state = state.loaded;
        this.render(this.src);
        next && next();
      })
      .catch(e => {
        this.state = state.loaded;
        this.render(this.error);
        console.warn(
          `load failed with src image(${this.src}) and the error msg is ${e.message}`
        );
        next && next();
      });
  }
}
export default function loadImage(src) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = function () {
      resolve();
      dispose();
    };
    image.onerror = function (e) {
      reject(e);
      dispose();
    };
    image.src = src;
    function dispose() {
      image.onload = image.onerror = null;
    }
  });
}

const DEFAULT_URL =
  "";

class Lazy {
  constructor(options) {
    this.managerQueue = [];
    this.initIntersectionObserver();

    this.loading = options.loading || DEFAULT_URL;
    this.error = options.error || DEFAULT_URL;
  }
}

const lazyPlugin = {
  install(app, options) {
    const lazy = new Lazy(options);
    app.directive("lazy", {
      mounted: lazy.add.bind(lazy)
    });
  }
};
